package app

import (
	"chatgpt/helper"
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/openai"
	"chatgpt/services/completion"
	"github.com/gin-gonic/gin"
)

func CompletionHandle(ctx *gin.Context) {
	question := ctx.Query("q")
	mod := ctx.Query("model")
	unafe := ctx.Query("unsafe")
	if !completion.CheckQuestion(question) {
		helper.Echo(ctx, int(code.DATA_NIL), "")
		return
	}
	if !openai.AppChatGPT.CheckQuestion(question) && !openai.AppChatGPT.Unsafe(question, unafe) {
		helper.Echo(ctx, int(code.SUCCESS), "抱歉没有找到与“"+question+"”相关的信息")
		return
	}
	uid := (helper.Uid(ctx))
	queue := completion.Mgr().Get(uid)
	nquestion := question
	if queue != nil {
		nquestion = queue.ConvPrompt(question)
	}

	mcode, replay := openai.RemoteApi(openai.OPENAI_COMPLETION, nquestion, map[string]string{
		"model":  mod,
		"smodel": ctx.Query("smodel"),
		"stops":  completion.Mgr().StopSequence(uid),
		"unsafe": openai.UNSAFE_MOD,
	})
	if mcode == code.SUCCESS {
		completion.Mgr().Add(uid, completion.NewDialogue(question, replay.Data.(string)))
	}
	helper.Echo(ctx, int(mcode), replay.Data)
	logq.InfoF("HANDLE.COMPLETION uid:%v ip:%v tokens:%v prompt:%s", uid, ctx.RemoteIP(), replay.Tokens, question)
	logq.DebugF("HANDLE.COMPLETION uid:%v ip:%v tokens:%v prompt-all:%s", uid, ctx.RemoteIP(), replay.Tokens, nquestion)
}

func ChatHandle(ctx *gin.Context) {
	question := ctx.Query("q")
	mod := ctx.Query("model")
	unafe := ctx.Query("unsafe")
	if !completion.CheckQuestion(question) {
		helper.Echo(ctx, int(code.DATA_NIL), "")
		return
	}
	if !openai.AppChatGPT.CheckQuestion(question) && !openai.AppChatGPT.Unsafe(question, unafe) {
		helper.Echo(ctx, int(code.SUCCESS), "抱歉没有找到与“"+question+"”相关的信息")
		return
	}

	mcode, replay := openai.RemoteApi(openai.OPENAI_CHAT, question, map[string]string{
		"model":  mod,
		"smodel": ctx.Query("smodel"),
		"stops":  ctx.Query("stop"),
		"unsafe": openai.UNSAFE_MOD,
	})
	helper.Echo(ctx, int(mcode), replay.Data)
}

func CompletionClearHandle(ctx *gin.Context) {
	uid := (helper.Uid(ctx))
	queue := completion.Mgr().Get(uid)
	if queue == nil {
		helper.Echo(ctx, int(code.SUCCESS), "")
		return
	}

	queue.Clear()
	helper.Echo(ctx, int(code.SUCCESS), "服务会话清理")
}
